package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//员工管理模块
@RestController //加上这个注解之后可以用来接收HTTP请求的类
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> param , HttpSession session){
        //1.接收请求参数
        String username = param.get("username");
        String password = param.get("password");
        //2.调用service实现登录
        ResultInfo resultInfo = employeeService.login(username, password);
        //3.判断登录状态
        if (resultInfo.getCode()==1){
            //登录成功
        session.setAttribute(Constant.SESSION_EMPLOYEE,resultInfo.getData());
        }
        //4.返回结果
        return resultInfo;
    }

    //员工退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(HttpSession session){
        //1.清理session
        session.invalidate();
        //2.返回结果
        return ResultInfo.success();
    }

    //员工列表
    @GetMapping("/employee/find")
    public ResultInfo findList(String name){ //1.接收请求参数
    //2.调用service查询
     List<Employee> employeeList =employeeService.findList(name);
    //3.封装到resultInfo返回
        return ResultInfo.success(employeeList);
    }
    //新增员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){ //接收post请求
        //调用service添加
        employeeService.save(employee);
        //返回成功
        return ResultInfo.success();
    }
    //回显员工
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable Long id){ //1.接收get请求方式参数
        //2.调用service查询
       Employee employee =  employeeService.findById(id);
        //3.返回成功
        return ResultInfo.success(employee);
    }
    //修改员工
    @PutMapping("/employee")
    public ResultInfo updateById(@RequestBody Employee employee){ //1.接收put请求参数
        //2.调用service修改
        employeeService.updateById(employee);
        //3.返回成功
        return ResultInfo.success();

    }
}
